package com.m3958.firstgwt.server.service;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Date;

import javax.persistence.EntityManager;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.model.VoteTpl;

import freemarker.cache.TemplateLoader;


@Singleton
public class VoteTplDbLoader implements TemplateLoader{
	
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;
	
	private static VoteTpl vt = new VoteTpl();
	static {
		vt.setContent("");
		vt.setUpdatedAt(new Date());
	}

	@Override
	public void closeTemplateSource(Object arg0) throws IOException {
		;
	}

	@Override
	public Object findTemplateSource(String vtplId) throws IOException {
		Object o = null;
		try {
			o = emp.get().find(VoteTpl.class, Integer.parseInt(vtplId));
		} catch (NumberFormatException e) {
			;
		} 
		if(o == null){
			return vt;
		}else{
			return o;
		}
		
	}

	@Override
	public long getLastModified(Object vtpl) {
		return ((VoteTpl)vtpl).getUpdatedAt().getTime();
	}

	@Override
	public Reader getReader(Object vtpl, String encode) throws IOException {
		return new StringReader(((VoteTpl)vtpl).getContent());
	}

}
